import React, { useState } from 'react';
import { Card, Tabs, Table, Button, Modal, Form, Input, Row, Col, Space, Popconfirm, message } from 'antd';
import { PlusOutlined, MinusCircleOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { TabPane } = Tabs;

interface Strategy {
  id: number;
  name: string;
  tianshiCondition: string[];
  diliCondition: string[];
  usageCount: number;
  successCount: number;
  successRate: string;
}

const StockSelectionStrategy: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingStrategy, setEditingStrategy] = useState<Strategy | null>(null);
  const [form] = Form.useForm();
  const [strategies, setStrategies] = useState<Strategy[]>([
    {
      id: 1,
      name: '趋势突破策略',
      tianshiCondition: ['市场上涨趋势', '大盘指数强势'],
      diliCondition: ['突破关键阻力位', '成交量配合'],
      usageCount: 25,
      successCount: 18,
      successRate: '72%'
    },
    {
      id: 2,
      name: '均线金叉策略',
      tianshiCondition: ['短期均线上穿长期均线', '市场情绪乐观'],
      diliCondition: ['成交量放大', '股价站稳均线'],
      usageCount: 30,
      successCount: 21,
      successRate: '70%'
    }
  ]);

  // 将数据扁平化处理，每个条件占一行
  const flattenedData = strategies.flatMap(strategy => {
    const maxConditions = Math.max(strategy.tianshiCondition.length, strategy.diliCondition.length);
    return Array.from({ length: maxConditions }, (_, index) => ({
      key: `${strategy.id}-${index}`,
      id: strategy.id,
      name: strategy.name,
      tianshiCondition: strategy.tianshiCondition[index] || '',
      diliCondition: strategy.diliCondition[index] || '',
      usageCount: strategy.usageCount,
      successCount: strategy.successCount,
      successRate: strategy.successRate,
      isFirstRow: index === 0,
      rowSpan: index === 0 ? maxConditions : 0,
    }));
  });

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: (value: number, record: any) => ({
        children: value,
        props: {
          rowSpan: record.rowSpan,
        },
      }),
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (value: string, record: any) => ({
        children: value,
        props: {
          rowSpan: record.rowSpan,
        },
      }),
    },
    {
      title: '天时条件',
      dataIndex: 'tianshiCondition',
      key: 'tianshiCondition',
    },
    {
      title: '地利条件',
      dataIndex: 'diliCondition',
      key: 'diliCondition',
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      width: 100,
      render: (value: number, record: any) => ({
        children: value,
        props: {
          rowSpan: record.rowSpan,
        },
      }),
    },
    {
      title: '成功次数',
      dataIndex: 'successCount',
      key: 'successCount',
      width: 100,
      render: (value: number, record: any) => ({
        children: value,
        props: {
          rowSpan: record.rowSpan,
        },
      }),
    },
    {
      title: '成功率',
      dataIndex: 'successRate',
      key: 'successRate',
      width: 100,
      render: (value: string, record: any) => ({
        children: value,
        props: {
          rowSpan: record.rowSpan,
        },
      }),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record: any) => {
        if (record.rowSpan === 0) return null;
        
        const strategy = strategies.find(s => s.id === record.id);
        return {
          children: (
            <Space size="small">
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => handleEdit(strategy)}
                style={{ color: '#64ffda', padding: 0 }}
              >
                编辑
              </Button>
              <Popconfirm
                title="确定要删除这个策略吗？"
                onConfirm={() => handleDelete(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="link"
                  icon={<DeleteOutlined />}
                  style={{ color: '#ff6b6b', padding: 0 }}
                >
                  删除
                </Button>
              </Popconfirm>
            </Space>
          ),
          props: {
            rowSpan: record.rowSpan,
          },
        };
      },
    }
  ];

  const showModal = () => {
    setEditingStrategy(null);
    setIsModalVisible(true);
  };

  const handleEdit = (strategy: Strategy | undefined) => {
    if (strategy) {
      setEditingStrategy(strategy);
      form.setFieldsValue({
        name: strategy.name,
        tianshiCondition: strategy.tianshiCondition,
        diliCondition: strategy.diliCondition,
      });
      setIsModalVisible(true);
    }
  };

  const handleDelete = (id: number) => {
    setStrategies(strategies.filter(strategy => strategy.id !== id));
    message.success('策略删除成功');
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      if (editingStrategy) {
        // 编辑模式
        const updatedStrategies = strategies.map(strategy =>
          strategy.id === editingStrategy.id
            ? {
                ...strategy,
                name: values.name,
                tianshiCondition: Array.isArray(values.tianshiCondition) ? values.tianshiCondition : [values.tianshiCondition],
                diliCondition: Array.isArray(values.diliCondition) ? values.diliCondition : [values.diliCondition],
              }
            : strategy
        );
        setStrategies(updatedStrategies);
        message.success('策略更新成功');
      } else {
        // 新增模式
        const newStrategy: Strategy = {
          id: Math.max(...strategies.map(s => s.id), 0) + 1,
          name: values.name,
          tianshiCondition: Array.isArray(values.tianshiCondition) ? values.tianshiCondition : [values.tianshiCondition],
          diliCondition: Array.isArray(values.diliCondition) ? values.diliCondition : [values.diliCondition],
          usageCount: 0,
          successCount: 0,
          successRate: '0%'
        };
        setStrategies([...strategies, newStrategy]);
        message.success('策略添加成功');
      }
      form.resetFields();
      setIsModalVisible(false);
      setEditingStrategy(null);
    }).catch(error => {
      console.error('表单验证失败:', error);
      message.error('表单验证失败，请检查输入');
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingStrategy(null);
    form.resetFields();
  };

  // 饼图数据
  const pieData = [
    { type: '波段复利', value: 35 },
    { type: '主线龙头', value: 28 },
    { type: '投机套利', value: 22 },
    { type: '价值低吸', value: 15 },
  ];

  // 柱状图数据
  const columnData = [
    { strategy: '波段复利', successRate: 68 },
    { strategy: '主线龙头', successRate: 75 },
    { strategy: '投机套利', successRate: 45 },
    { strategy: '价值低吸', successRate: 82 },
  ];

  // 简单的饼图组件
  const SimplePieChart = () => {
    const colors = ['#64ffda', '#ff6b6b', '#4ecdc4', '#45b7d1'];
    const total = pieData.reduce((sum, item) => sum + item.value, 0);
    let currentAngle = 0;

    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '300px' }}>
        <div style={{ position: 'relative', width: '200px', height: '200px' }}>
          <svg width="200" height="200" style={{ transform: 'rotate(-90deg)' }}>
            {pieData.map((item, index) => {
              const percentage = (item.value / total) * 100;
              const angle = (item.value / total) * 360;
              const x1 = 100 + 80 * Math.cos((currentAngle * Math.PI) / 180);
              const y1 = 100 + 80 * Math.sin((currentAngle * Math.PI) / 180);
              const x2 = 100 + 80 * Math.cos(((currentAngle + angle) * Math.PI) / 180);
              const y2 = 100 + 80 * Math.sin(((currentAngle + angle) * Math.PI) / 180);
              const largeArcFlag = angle > 180 ? 1 : 0;
              
              const pathData = [
                `M 100 100`,
                `L ${x1} ${y1}`,
                `A 80 80 0 ${largeArcFlag} 1 ${x2} ${y2}`,
                'Z'
              ].join(' ');
              
              currentAngle += angle;
              
              return (
                <path
                  key={index}
                  d={pathData}
                  fill={colors[index]}
                  stroke="#112240"
                  strokeWidth="2"
                />
              );
            })}
          </svg>
        </div>
        <div style={{ marginLeft: '20px' }}>
          {pieData.map((item, index) => (
            <div key={index} style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
              <div
                style={{
                  width: '12px',
                  height: '12px',
                  backgroundColor: colors[index],
                  marginRight: '8px',
                  borderRadius: '2px'
                }}
              />
              <span style={{ color: '#ccd6f6', fontSize: '14px' }}>
                {item.type}: {((item.value / total) * 100).toFixed(1)}%
              </span>
            </div>
          ))}
        </div>
      </div>
    );
  };

  // 简单的柱状图组件
  const SimpleBarChart = () => {
    const maxRate = Math.max(...columnData.map(item => item.successRate));
    
    return (
      <div style={{ padding: '20px' }}>
        <div style={{ display: 'flex', alignItems: 'end', height: '200px', gap: '20px' }}>
          {columnData.map((item, index) => (
            <div key={index} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <div
                style={{
                  width: '40px',
                  height: `${(item.successRate / maxRate) * 160}px`,
                  backgroundColor: '#64ffda',
                  borderRadius: '4px 4px 0 0',
                  marginBottom: '8px',
                  position: 'relative'
                }}
              >
                <div
                  style={{
                    position: 'absolute',
                    top: '-25px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    color: '#ccd6f6',
                    fontSize: '12px',
                    fontWeight: 'bold'
                  }}
                >
                  {item.successRate}%
                </div>
              </div>
              <div style={{ color: '#ccd6f6', fontSize: '12px', textAlign: 'center', wordBreak: 'break-all' }}>
                {item.strategy}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  const renderStrategyTable = () => (
    <Card
      title="策略列表"
      extra={
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={showModal}
          style={{ backgroundColor: '#64ffda', borderColor: '#64ffda', color: '#112240' }}
        >
          新增策略
        </Button>
      }
      style={{ backgroundColor: '#112240', borderColor: '#233554' }}
      headStyle={{ backgroundColor: '#112240', borderBottomColor: '#233554', color: '#64ffda' }}
      bodyStyle={{ backgroundColor: '#112240' }}
    >
      <Table
        columns={columns}
        dataSource={flattenedData}
        rowKey="key"
        pagination={false}
        style={{ backgroundColor: '#112240', borderColor: '#64ffda' }}
        className="dark-table"
        bordered
      />
    </Card>
  );

  return (
    <div style={{ padding: '20px', backgroundColor: '#0a192f', minHeight: '100vh' }}>
      {/* 上方区域 - 标签页 */}
      <Card style={{ backgroundColor: '#112240', borderColor: '#233554', marginBottom: '20px' }}>
        <Tabs 
          defaultActiveKey="1"
          style={{ color: '#ccd6f6' }}
          className="dark-tabs"
          tabBarStyle={{ backgroundColor: '#112240', padding: '0 10px', borderRadius: '4px' }}
          tabBarGutter={10}
        >
          <TabPane 
            tab={<span style={{ backgroundColor: '#233554', padding: '8px 16px', borderRadius: '4px', fontSize: '16px' }}>波段复利</span>} 
            key="1"
          >
            {renderStrategyTable()}
          </TabPane>
          <TabPane 
            tab={<span style={{ backgroundColor: '#233554', padding: '8px 16px', borderRadius: '4px', fontSize: '16px' }}>主线龙头</span>} 
            key="2"
          >
            {renderStrategyTable()}
          </TabPane>
          <TabPane 
            tab={<span style={{ backgroundColor: '#233554', padding: '8px 16px', borderRadius: '4px', fontSize: '16px' }}>投机套利</span>} 
            key="3"
          >
            {renderStrategyTable()}
          </TabPane>
          <TabPane 
            tab={<span style={{ backgroundColor: '#233554', padding: '8px 16px', borderRadius: '4px', fontSize: '16px' }}>价值低吸</span>} 
            key="4"
          >
            {renderStrategyTable()}
          </TabPane>
        </Tabs>
      </Card>

      {/* 下方区域 - 统计图表 */}
      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Card
            title="策略分布统计"
            style={{ backgroundColor: '#112240', borderColor: '#233554' }}
            headStyle={{ backgroundColor: '#112240', borderBottomColor: '#233554', color: '#64ffda' }}
            bodyStyle={{ backgroundColor: '#112240' }}
          >
            <SimplePieChart />
          </Card>
        </Col>
        <Col span={12}>
          <Card
            title="策略成功率统计"
            style={{ backgroundColor: '#112240', borderColor: '#233554' }}
            headStyle={{ backgroundColor: '#112240', borderBottomColor: '#233554', color: '#64ffda' }}
            bodyStyle={{ backgroundColor: '#112240' }}
          >
            <SimpleBarChart />
          </Card>
        </Col>
      </Row>

      {/* 新增策略弹窗 */}
      <Modal
        title={editingStrategy ? "编辑策略" : "新增策略"}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
        style={{ color: '#ccd6f6' }}
        className="dark-modal"
      >
        <Form
          form={form}
          layout="vertical"
          style={{ color: '#ccd6f6' }}
        >
          <Form.Item
            label="策略名称"
            name="name"
            rules={[{ required: true, message: '请输入策略名称' }]}
          >
            <Input placeholder="请输入策略名称" />
          </Form.Item>
          <Form.List name="tianshiCondition">
            {(fields, { add, remove }) => (
              <>
                <Form.Item label="天时条件" required>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                      <Form.Item
                        {...restField}
                        name={name}
                        rules={[{ required: true, message: '请输入天时条件' }]}
                        style={{ margin: 0, flex: 1 }}
                      >
                        <Input placeholder="请输入天时条件" />
                      </Form.Item>
                      {fields.length > 1 && (
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      )}
                    </Space>
                  ))}
                  <Form.Item style={{ margin: 0 }}>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                      添加天时条件
                    </Button>
                  </Form.Item>
                </Form.Item>
              </>
            )}
          </Form.List>
          <Form.List name="diliCondition">
            {(fields, { add, remove }) => (
              <>
                <Form.Item label="地利条件" required>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                      <Form.Item
                        {...restField}
                        name={name}
                        rules={[{ required: true, message: '请输入地利条件' }]}
                        style={{ margin: 0, flex: 1 }}
                      >
                        <Input placeholder="请输入地利条件" />
                      </Form.Item>
                      {fields.length > 1 && (
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      )}
                    </Space>
                  ))}
                  <Form.Item style={{ margin: 0 }}>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                      添加地利条件
                    </Button>
                  </Form.Item>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>

      <style jsx global>{`
        .dark-table .ant-table {
          background-color: #112240 !important;
          color: #ccd6f6 !important;
        }
        .dark-table .ant-table-thead > tr > th {
          background-color: #233554 !important;
          color: #64ffda !important;
          border-bottom: 1px solid #233554 !important;
          border-right: 1px solid #233554 !important;
        }
        .dark-table .ant-table-tbody > tr > td {
          background-color: #112240 !important;
          color: #ccd6f6 !important;
          border-bottom: 1px solid #233554 !important;
          border-right: 1px solid #233554 !important;
        }
        .dark-table .ant-table-tbody > tr:hover > td {
          background-color: #233554 !important;
        }
        .dark-table .ant-table-bordered .ant-table-container {
          border: 1px solid #233554 !important;
        }
        .dark-table .ant-table-bordered .ant-table-thead > tr > th,
        .dark-table .ant-table-bordered .ant-table-tbody > tr > td {
          border-right: 1px solid #233554 !important;
        }
        .dark-tabs .ant-tabs-tab {
          color: #ccd6f6 !important;
        }
        .dark-tabs .ant-tabs-tab-active {
          color: #64ffda !important;
        }
        .dark-tabs .ant-tabs-ink-bar {
          background-color: #64ffda !important;
        }
        .dark-modal .ant-modal-content {
          background-color: #ffffff !important;
          color: #333333 !important;
        }
        .dark-modal .ant-modal-header {
          background-color: #ffffff !important;
          border-bottom: 1px solid #e8e8e8 !important;
        }
        .dark-modal .ant-modal-title {
          color: #1890ff !important;
        }
        .dark-modal .ant-form-item-label > label {
          color: #333333 !important;
        }
        .dark-modal .ant-input {
          background-color: #ffffff !important;
          border-color: #d9d9d9 !important;
          color: #333333 !important;
        }
        .dark-modal .ant-btn-primary {
          background-color: #1890ff !important;
          border-color: #1890ff !important;
        }
        .dark-modal .ant-btn-dashed {
          background-color: #f5f5f5 !important;
          border-color: #d9d9d9 !important;
          color: #666666 !important;
        }
        .dark-modal .anticon-minus-circle {
          color: #ff4d4f !important;
        }
        .ant-popover {
          z-index: 1060 !important;
        }
        .ant-popover-inner {
          background-color: #112240 !important;
          border: 1px solid #233554 !important;
        }
        .ant-popover-title {
          background-color: #112240 !important;
          color: #64ffda !important;
          border-bottom: 1px solid #233554 !important;
        }
        .ant-popover-inner-content {
          background-color: #112240 !important;
          color: #ccd6f6 !important;
        }
        .ant-popover-arrow {
          border-top-color: #233554 !important;
          border-left-color: #233554 !important;
        }
      `}</style>
    </div>
  );
};

export default StockSelectionStrategy;
